<?php
class Auth extends Model
{
    public $db;
    private $user;
    private $md5Pass;

    public function __construct ()
    {
        $this->db = loadLib('DbMysql');
    }

    public function login($user, $pass)
    {
        global $ENV;
        $auth = $this->db->fetchRow('config', 'name="auth"');
        list($this->user, $this->md5Pass) = explode('#', $auth['value']);
        if ($user == $this->user && md5($pass) == $this->md5Pass){
            $_SESSION['login.lastActive'] = $ENV['time'];
            $_SESSION['login.user'] = $user;
            $_SESSION['login.pass'] = $this->md5Pass;
            $_SESSION['login'] = true;
            debug('auth: user logged in.');
            return true;
        }
            return false;
    }

    public function isLogin()
    {
        global $ENV;
        if (!$ENV['app.auth'])
            return true;
        return isset($_SESSION['login']) ? $_SESSION['login'] : false;
    }

    public function logout()
    {
        global $ENV;
        session_destroy();//delete session file
        setcookie($ENV['sess.name'], '', $ENV['time'] - 86400, '/');//delete PHPSESSID
        unset($_SESSION['login.user']);
        unset($_SESSION['login.pass']);
        unset($_SESSION['login']);
        debug('auth: user logged out.');
    }
}
?>
